import { useEffect, useState, useRef } from 'react';
import { message } from 'antd';
import { ProFormText, ModalForm, ProFormSwitch } from '@ant-design/pro-components';
import { isLocal, isSuccess } from '@/utils';
import { addZhimaApi, editZhimaApi } from '@/api';

export default function AddZhiMa({ open, setOpen, formData, reload }: any) {
  const [txt, setTxt] = useState('');
  const formRef: any = useRef('');
  console.log('formData: ', formData);

  useEffect(() => {
    setTxt(formData?.id ? '编辑' : '新增');
    if (open) initData();
  }, [open]);

  // 初始化数据
  const initData = () => {
    formRef?.current?.resetFields();
    if (formData?.id) {
      formRef?.current?.setFieldsValue(formData);
      return;
    }
    // 新增
    formRef?.current?.setFieldsValue({
      is_active: true,
    });
    if (isLocal()) {
      formRef?.current?.setFieldsValue({
        name: '账户2',
        key: 'key2',
        secret: 'secret2',
      });
    }
  };

  // 提交
  const submit = async () => {
    let formatData = await formRef?.current?.validateFieldsReturnFormatValue();
    console.log('格式化后的表单数据: ', formatData);
    let res: any;
    if (!formData?.id) {
      // 新增
      res = await addZhimaApi(formatData);
    } else {
      // 编辑
      res = await editZhimaApi({ ...formatData, id: formData?.id });
    }
    if (!isSuccess(res)) return;
    message.success(txt + '成功');
    reload();
    setOpen(false);
  };

  return (
    <ModalForm
      title={`${txt}账户`}
      formRef={formRef}
      open={open}
      layout="horizontal"
      onFinish={submit}
      onOpenChange={setOpen}
      labelCol={{ span: 4 }}
    >
      <br />
      <ProFormText name="name" label="芝麻账户" placeholder="请输入" rules={[{ required: true }]} />
      <ProFormText name="key" label="apiKey" placeholder="请输入" rules={[{ required: true }]} />
      <ProFormText
        name="secret"
        label="apiSecret"
        placeholder="请输入"
        rules={[{ required: true }]}
      />
      <ProFormSwitch name="is_active" label="是否开启" rules={[{ required: true }]} />
    </ModalForm>
  );
}
